package org.ielts.service.security;

import java.util.Arrays;
import java.util.HashSet;

import org.ielts.domain.security.Role;
import org.ielts.domain.security.User;
import org.ielts.repository.security.UserRepository;
import org.ielts.repository.security.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserRoleService {

	@Autowired
	UserRoleRepository userRoleRepository;

	@Transactional
	public Page<User> listUserInRole(String roleId, String userName, Pageable pageable) {
		Role role = new Role();
		role.setId(roleId);

		Page<User> users = userRoleRepository.listUserInRole(role, userName, pageable);

		return users;
	}

	@Transactional
	public void addUserInRole(String[] userIds, String roleId) {
		Role role = new Role();
		role.setId(roleId);

		HashSet<String> ids = new HashSet<String>(Arrays.asList(userIds));

		for (String id : ids) {
			User user = userRepositoryr.findOne(id);
			userRoleRepository.addUserInRole(user, role);
		}
	}

	@Autowired
	UserRepository userRepositoryr;

	@Transactional
	public void removeUserFromRole(String[] userIds, String roleId) {
		Role role = new Role();
		role.setId(roleId);

		for (String id : userIds) {
			User user = new User();
			user.setId(id);

			userRoleRepository.removeUserFromRole(user, role);
		}

	}
}
